#!/bin/bash

# ==========================================
# 儿童积分系统 - 自动化部署脚�?
# ==========================================

set -e  # 遇到错误立即退�?

echo "======================================"
echo "  开始部署儿童积分系�?
echo "======================================"

# 颜色定义
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 1. 检查环�?
echo -e "\n${YELLOW}[1/8] 检查部署环�?..${NC}"

if ! command -v node &> /dev/null; then
    echo -e "${RED}错误: Node.js 未安装，请先安装 Node.js 18+${NC}"
    exit 1
fi

if ! command -v npm &> /dev/null; then
    echo -e "${RED}错误: npm 未安�?{NC}"
    exit 1
fi

if ! command -v pm2 &> /dev/null; then
    echo -e "${YELLOW}PM2 未安装，正在安装...${NC}"
    npm install -g pm2
fi

echo -e "${GREEN}�?环境检查通过${NC}"

# 2. 检查环境变量文�?
echo -e "\n${YELLOW}[2/8] 检查环境变量配�?..${NC}"

if [ ! -f .env ]; then
    echo -e "${RED}错误: .env 文件不存�?{NC}"
    echo -e "${YELLOW}请根�?.env.production 模板创建 .env 文件${NC}"
    exit 1
fi

echo -e "${GREEN}�?环境变量文件存在${NC}"

# 3. 安装依赖
echo -e "\n${YELLOW}[3/8] 安装依赖�?..${NC}"
npm ci --production=false

echo -e "${GREEN}�?依赖安装完成${NC}"

# 4. 生成 Prisma Client
echo -e "\n${YELLOW}[4/8] 生成 Prisma Client...${NC}"
npx prisma generate

echo -e "${GREEN}�?Prisma Client 生成完成${NC}"

# 5. 数据库迁�?
echo -e "\n${YELLOW}[5/8] 执行数据库迁�?..${NC}"
echo -e "${YELLOW}注意: 如果是首次部署，请确保数据库已创�?{NC}"

read -p "是否执行数据库迁移？(y/n) " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    npx prisma migrate deploy
    echo -e "${GREEN}�?数据库迁移完�?{NC}"
else
    echo -e "${YELLOW}跳过数据库迁�?{NC}"
fi

# 6. 构建生产版本
echo -e "\n${YELLOW}[6/8] 构建生产版本...${NC}"
npm run build

echo -e "${GREEN}�?构建完成${NC}"

# 7. 创建日志目录
echo -e "\n${YELLOW}[7/8] 创建日志目录...${NC}"
mkdir -p logs

echo -e "${GREEN}�?日志目录创建完成${NC}"

# 8. 启动/重启应用
echo -e "\n${YELLOW}[8/8] 启动应用...${NC}"

if pm2 list | grep -q "child-points-system"; then
    echo -e "${YELLOW}应用已运行，执行重启...${NC}"
    pm2 reload ecosystem.config.cjs --update-env
    echo -e "${GREEN}�?应用重启成功${NC}"
else
    echo -e "${YELLOW}首次启动应用...${NC}"
    pm2 start ecosystem.config.cjs
    pm2 save
    echo -e "${GREEN}�?应用启动成功${NC}"
fi

# 显示应用状�?
echo -e "\n${GREEN}======================================"
echo "  部署完成�?
echo "======================================${NC}"
echo ""
pm2 status
echo ""
echo -e "${YELLOW}常用命令:${NC}"
echo "  pm2 logs child-points-system  # 查看日志"
echo "  pm2 restart child-points-system  # 重启应用"
echo "  pm2 stop child-points-system  # 停止应用"
echo "  pm2 monit  # 监控应用"
echo ""
echo -e "${GREEN}应用已在端口 3000 运行${NC}"
